﻿using System.Text;
using NPOI.SS.UserModel;

namespace ExcelExport
{
    public class Utility
    {
        public static bool WriteFile(string filePath, string data)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            string dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            bool result = true;
            try
            {
                fs = new FileStream(filePath, FileMode.Create);
                sw = new StreamWriter(fs);
                sw.Write(data);
            }
            catch (Exception ex)
            {
                string fileName = Path.GetFileName(filePath);
                result = false;
                Debug.Error("写入文件错误，{0}文件没有正确导出,错误信息:{1}", fileName, ex.ToString());
            }
            finally
            {
                if (sw != null)
                    sw.Close();
                if (fs != null)
                    fs.Close();
            }
            return result;
        }

        /// 剔除中文和默认sheet Name
        public static bool IsValidSheets(string sheetName)
        {
            char[] c = sheetName.ToCharArray();
            if (!Util.IsSubTable)
                return true;
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] >= 0x4e00 && c[i] <= 0x9fbb)
                    return false;//存在汉字字符返回
            }
            if (sheetName.IndexOf("Sheet") != -1)
            {
                return false;
            }
            return true;
        }

        public static bool IsChinese(string val)
        {
            char[] c = val.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] >= 0x4e00 && c[i] <= 0x9fbb)
                    return true;//存在汉字字符返回
            }
            return false;
        }

        public static string FirstCharToUpper(string input)
        {
            if (String.IsNullOrEmpty(input))
                throw new ArgumentException("ARGH!");

            return input.First().ToString().ToUpper() + input.Substring(1);
        }

        public static string DirectoryOper(string excelDirPath)
        {
            string tmpPath = string.Format("{0}{1}", excelDirPath, "tmp");
            if (!Directory.Exists(tmpPath))
            {
                Directory.CreateDirectory(tmpPath);
            }
            return tmpPath;
        }

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail, error:" + ex.Message);
            }
        }

        public static IWorkbook ReadExcel(string excelPath, ref IFormulaEvaluator evalor)
        {
            IWorkbook workbook = null;

            using (FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                //兼容2003/2007
                workbook = WorkbookFactory.Create(fs);
                evalor = WorkbookFactory.CreateFormulaEvaluator(workbook);
            }
            return workbook;
        }

        public static string GetCellValue(ICell cell, IFormulaEvaluator evalor)
        {
            string result = string.Empty;
            if (cell == null)
                return result;
            switch (cell.CellType)
            {
                case CellType.Boolean:
                    result = cell.BooleanCellValue.ToString();
                    break;
                case CellType.Error:
                    result = cell.ErrorCellValue.ToString();
                    break;
                case CellType.Formula:
                    if (evalor == null)
                        result = cell.CellFormula.ToString();
                    else
                    {
                        try
                        {
                            var formulaValue = evalor.Evaluate(cell);
                            //公式仅支持字符串和数字两种
                            if (formulaValue.CellType == CellType.Numeric)
                            {
                                result = formulaValue.NumberValue.ToString();
                            }
                            else if (formulaValue.CellType == CellType.String)
                            {
                                result = formulaValue.StringValue;
                            }
                        }
                        catch
                        {
                            result = cell.CellFormula.ToString();
                        }
                    }
                    break;
                case CellType.Numeric:
                    result = cell.NumericCellValue.ToString();
                    break;
                case CellType.String:
                    result = cell.StringCellValue;
                    break;

            }
            return result.Trim();
        }
    }
}
